﻿using AppDataStruct;
using ComLib.ComType;
using EECMISWS;
using KWindow.KPageCore;
using LogLib;
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageQueryApplyInfo : PageControlBase
    {    
        private bool _bCancellFlag = false;

        private SFZInfo _sfz= new SFZInfo();

        private bool _queryResult = false;

        /// <summary>
        /// 查询是否有预约申请信息
        /// </summary>
        private bool _hasAppointmentData = false;

        private PreApplyInfo _appInfo = null;

        private WebDataAccess _webAccess = null;

        private PictureBox pictureBox1 = null;

        private Image imgSelecting = null;

        private Image imgSelectFailed = null;

        private Label labelInputTip = null;

        private bool HZChecked = false;

        private bool SCZChecked = false;

        private bool DLZChecked = false;

        public PageQueryApplyInfo()
        {
            InitializeComponent();
            SetProcessBase(ProcessQueryApplyInfo.Instance);
        }

        private void GetControls()
        {
            pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
            imgSelectFailed = GetImage("SelectFailed");
            imgSelecting = GetImage("Selecting");
            labelInputTip = GetControl<Label>("labelInputTip") as Label;
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            GetControls();          
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            HZChecked = false;
            SCZChecked = false;
            DLZChecked = false;
            _bCancellFlag = false;
            pictureBox1.Image = imgSelecting;
            _webAccess = WebDataAccess.Instance;
            _appInfo = Process.GetValue<PreApplyInfo>("PreApplyInfo");
            _queryResult = false;
            _hasAppointmentData = false;
            _sfz = Process.GetValue<SFZInfo>("SFZInfo");          
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            if (!string.IsNullOrEmpty(_appInfo.HZSQ.YWBH))
            {
                HZChecked = true;
            }
            if (!string.IsNullOrEmpty(_appInfo.SCZSQ.YWBH))
            {
                SCZChecked = true;
            }
            if (!string.IsNullOrEmpty(_appInfo.DLZSQ.YWBH))
            {
                DLZChecked = true;
            }
            Process.SetValue("SCZChecked", SCZChecked);
            Process.SetValue("HZChecked", HZChecked);
            Process.SetValue("DLZChecked", DLZChecked);
            Process.SetValue("PreApplyInfo", _appInfo);
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            _hasAppointmentData = false;
            _appInfo = null;
            HZChecked = false;
            SCZChecked = false;
            DLZChecked = false;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
            if (IsMainPage)
            {
                BeginQuerying();
            }            
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            _bCancellFlag = true;
            base.OnCountdownCompleted(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnBack_Click(sender, e);
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnNext_Click(sender, e);
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            StopCountdown();
            _bCancellFlag = true;
            AbortWork();
            base.btnCancel_Click(sender, e);
        }

        private void BeginQuerying()
        {
            if (_sfz == null)
            {
                MessageBox.Show("无有效的身份证信息.");
                StopCountdown();
                return;
            }
            WebDataAccess webAccess = WebDataAccess.Instance;
            if (!webAccess.Enabled)
            {
                MessageBox.Show("全国版接口未启用.");
                StopCountdown();
                base.btnNext_Click(null,null);
                return;
            }
            Task.Factory.StartNew(() =>
            {
                QueryApplyInfo();
            });
        }

        private void QueryApplyInfo()
        {        
            if (!_webAccess.Inited)
            {
                if (!_webAccess.Login())
                {
                    OnQueryFailed(_webAccess.ErrorMessage);
                    return ;
                }
            }
            if (_webAccess.QueryAppointment(_sfz.SFZH, ref _appInfo, out _hasAppointmentData))
            {
                OnQueryCompleted();
            }
            else
            {
                OnQueryFailed(_webAccess.ErrorMessage);
            }
        }

        private void OnQueryCompleted()
        {
            if(_bCancellFlag)
            {
                return;
            }
            _queryResult = true;
            Log.WriteAsync("查询预约申请信息成功!");
            StopCountdown();
            Action handler = () =>
            {
                UpdateData();             
                if(_hasAppointmentData)
                {
                    Log.WriteAsync("预约申请信息已存在，直接打印表格。");
                    if (HZChecked && _config.WorkFlow.Signature) // 申请护照需要手写签名
                    {
                        Process.ToAny("YSLPages.PageSignature");
                    }
                    else
                    {
                        Process.ToAny("YSLPages.PageUploading");
                    }                    
                }
                else
                {
                    if(UserAction == UserApplyAction.OnlyWeiYinTB)
                    {
                        MessageBox.Show("没有查询到预约申请信息, 结束申请.");
                        CountdownSecond = 10;
                        StartCountdown();
                    }
                    else
                    {
                        Log.WriteAsync("没有预约申请信息，开始填写申请信息。");
                        Process.ToNext();
                    }                   
                }
            };
            this.Invoke(handler);
        }

        private void OnQueryFailed(string outParams)
        {
            if (_bCancellFlag)
            {
                return;
            }

            string msg = string.Format("查询预约申请信息失败: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                pictureBox1.Image = imgSelectFailed;
                SetTips(msg);
                CountdownSecond = 10;
                StartCountdown();
            };
            this.Invoke(handler, msg);
        }

        private void SetTips(string content)
        {
            labelInputTip.Text = content;
            int w = labelInputTip.Width;
            int x = (this.Width - w) / 2;
            labelInputTip.Left = x;
        }
    }
}
